/*
 * @Author: liuqiang
 * @Date: 2021-02-20 18:07:29
 * @Last Modified by:   liuqiang
 * @Last Modified time: 2021-02-20 18:07:29
 */
const { checkToken } = require('./jwt');
const EXCLUDE = {
  user: ['isLogin', 'login'],
};

// 将需要验证的路由数组化
const EXCLUDE_ARRAY = Object.keys(EXCLUDE)
  .map((key) => {
    const paths = EXCLUDE[key].map((item) => `/${key}/${item}`);
    return paths;
  })
  .flat();

async function beforeRouter(ctx, next) {
  const { path, headers } = ctx;
  if (EXCLUDE_ARRAY.includes(path)) {
    await next();
    return;
  }
  const { authorization: token } = headers;
  let isPermission = false;
  try {
    await checkToken(token);
    isPermission = true;
  } catch ({ code, msg }) {
    ctx.body = {
      err: -99,
      msg: msg || '校验token发生错误',
    };
    return;
  }
  if (isPermission) {
    await next();
  }
}

module.exports = {
  beforeRouter,
};
